class BallAiSystem extends System {
	constructor(world) {
		super(world);
	}

    getPlayerEntity() {
        for (const entity of this.getWorld().getEntities()) {
            if (entity.getComponent(PlayerControllerComponent)) {
                return entity;
            }
        }
    }

	execute() {
		const player = this.getPlayerEntity();
		const {x: xPlayer, y: yPlayer} = player.getComponent(PositionComponent);
        for (const entity of this.getWorld().getEntities()) {
            const ballComponent = entity.getComponent(BallComponent);
            const positionComponent = entity.getComponent(PositionComponent);
            const playerControllerComponent = entity.getComponent(PlayerControllerComponent);
            if (ballComponent && positionComponent && !playerControllerComponent) {
				const {x, y} = positionComponent;
				const scalar = config.ballSpeed * time.delta;
				const xDirection = xPlayer - x;
				const yDirection = yPlayer - y;
                const length = Math.sqrt(Math.pow(xDirection, 2) + Math.pow(yDirection, 2));
                positionComponent.x += xDirection / length * scalar;
                positionComponent.y += yDirection / length * scalar;

                for (const target of this.getWorld().getEntities()) {
                    if (target !== entity && !target.getComponent(PlayerControllerComponent) && CollisionSystem.collide(entity, target)) {
                        positionComponent.x = x;
                        positionComponent.y = y;
                    }
                }
            }
        }
	}
}